﻿
using K4os.Compression.LZ4;
using K4os.Compression.LZ4.Streams;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MX.Core.Compress
{
    public static class LZ4Helper
    {
        const int compressRatio = 500;//最大压缩比
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        static public byte[] Compress(byte[] data)
        {

            using (MemoryStream ms = new MemoryStream(data))
            {
                using (var compressStream = LZ4Stream.Decode(ms))
                {
                    var compressData = new byte[ms.Length];
                    int count = compressStream.Read(compressData, 0, compressData.Length);
                    Array.Resize(ref compressData, count);
                    return compressData;
                }
            }
        }

        /// <summary>
        /// 解压缩
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        static public byte[] Decompress(byte[] data)
        {
            using (MemoryStream ms = new MemoryStream(data))
            {
                using (var compressStream = LZ4Stream.Decode(ms))
                {
                    byte[] decompress = new byte[data.Length * compressRatio];
                    int count = compressStream.Read(decompress, 0, decompress.Length);
                    Array.Resize(ref decompress, count);
                    return decompress;
                }
            }
        }
    }
}
